package homework;

import cn.hutool.core.util.StrUtil;

import java.net.Socket;
import java.util.List;
import java.util.Objects;

public class RequestProcessor extends Thread {

    private Socket socket;
    private Server server;
    private Mapper mapper;

    public RequestProcessor(Socket socket,Server server,Mapper mapper) {
        this.socket = socket;
        this.server = server;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        try {
            // 从输入流中获取请求信息
            // 封装Request与Response对象
            Request request = new Request(socket.getInputStream());
            Response response = new Response(socket.getOutputStream());

            String url = request.getUrl();
            String address = request.getAddress();
            String port = request.getPort();

            String port1 = server.getService().getConnector().getPort();
            String hostName = server.getService().getEngine().getHost().getName();
            // 记录是否找到servlet
            Boolean isExistServlet = false;
            // 验证host与post
            if(address.equals(hostName) && port.equals(port1)){
                // 根据url查找对应的servlet
                Mapper.MappedHost mappedHost = mapper.getHosts().get(hostName);
                List<String> split = StrUtil.split(url, '/', true, true);
                String appName = split.get(0);

                Mapper.MappedContext mappedContext = mappedHost.getContexts().get(appName);
                // 验证项目名
                if(!Objects.isNull(mappedContext)){
                    StringBuilder path = new StringBuilder("/");
                    for (int i = 0; i < split.size(); i++) {
                        path.append(split.get(i));
                    }
                    Mapper.MappedWrapper mappedWrapper = mappedContext.getWrappers().get(path.toString());
                    // 验证servlet地址
                    if(!Objects.isNull(mappedWrapper)){
                        isExistServlet = true;
                        Servlet servlet = mappedWrapper.getServlet();
                        servlet.service(request,response);
                    }
                }
            }
            // 不存在Servlet，输出静态文件
            if(!isExistServlet){
                response.outputHtml(url);
            }

            socket.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
